package com.backend.modules.task.service;

import com.backend.common.event.TaskSubmissionEvent;
import com.backend.modules.system.entity.SysUser;
import com.backend.modules.task.dto.FileAuditResult;
import com.backend.modules.task.entity.Task;
import com.backend.modules.task.entity.TaskSubmission;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 通知服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationService {

    private final EmailService emailService;

    /**
     * 发送AI审核不通过通知
     * 
     * @param submission  提交记录
     * @param auditResult 审核结果
     */
    @Transactional
    public void sendAIRejectionNotification(TaskSubmission submission, FileAuditResult auditResult) {
        try {
            Task task = submission.getTask();
            SysUser student = submission.getStudent();
            
            // 构建通知内容
            String title = String.format("AI审核不通过：%s", task.getName());
            String content = String.format("您提交的任务《%s》未通过AI格式审核，原因：%s", 
                    task.getName(), auditResult.getReason());
            
            // 记录日志
            log.info("发送AI审核不通过通知: 学生={}, 任务={}, 原因={}", 
                    student.getUsername(), task.getName(), auditResult.getReason());
            
            // 发送邮件通知
            emailService.sendAIRejectionEmail(student, task, auditResult);
        } catch (Exception e) {
            log.error("发送AI审核不通过通知失败", e);
        }
    }
    
    /**
     * 监听任务提交事件
     */
    @Async
    @EventListener
    @Transactional(readOnly = true)
    public void handleTaskSubmissionEvent(TaskSubmissionEvent event) {
        TaskSubmission submission = event.getSubmission();
        boolean approved = event.isApproved();
        
        Task task = submission.getTask();
        SysUser student = submission.getStudent();
        
        // 预先获取需要使用的属性，避免懒加载问题
        String studentUsername = student.getUsername();
        String studentRealName = student.getRealName();
        String studentEmail = student.getEmail();
        Long studentId = student.getId();
        
        String taskName = task.getName();
        String reviewComment = submission.getReviewComment();
        
        try {
            if (approved) {
                // 提交通过
                String title = String.format("提交审核通过：%s", taskName);
                String content = String.format("您提交的任务《%s》已审核通过", taskName);
                
                // 记录日志
                log.info("发送提交审核通过通知: 学生={}, 任务={}", studentUsername, taskName);
            } else {
                // 教师审核不通过
                String title = String.format("提交审核不通过：%s", taskName);
                String content = String.format("您提交的任务《%s》未通过审核，原因：%s", 
                        taskName, reviewComment);
                
                // 记录日志
                log.info("发送提交审核不通过通知: 学生={}, 任务={}, 原因={}", 
                        studentUsername, taskName, reviewComment);
                
                // 发送邮件通知
                emailService.sendTeacherRejectionEmail(student, task, reviewComment);
            }
        } catch (Exception e) {
            log.error("处理任务提交事件失败", e);
        }
    }
    
    /**
     * 发送通知（此方法由系统中的通知模块提供）
     */
    public void send(Long receiverId, String title, String content, Object notificationType, Long relatedId) {
        // 记录日志
        log.info("发送通知: 接收者={}, 标题={}, 内容={}", receiverId, title, content);
    }
} 